package com.joyxy.easy.manger;

import cn.sanenen.dm.base.DmApiCache;
import com.joyxy.easy.entity.WindowContext;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class WindowManager {
    private static final Map<Long, WindowContext> contexts = new ConcurrentHashMap<>();
    public static void bindWindow(long hwnd) {
        if (!contexts.containsKey(hwnd)) {
            WindowContext context = new WindowContext(hwnd);
            contexts.put(hwnd, context);
        }
    }

    public static void unbindWindow(long hwnd) {
        WindowContext windowContext = contexts.get(hwnd);
        if (windowContext != null) {
            windowContext.stop();
            WindowContext context = contexts.remove(hwnd);
            if (context != null) {
                context.stopMonitoring();
                DmApiCache.releaseInstance(hwnd);
            }
        }

    }

    public static List<WindowContext> getActiveWindows() {
        return contexts.values().stream()
                .filter(WindowContext::isActive)
                .collect(Collectors.toList());
    }

    public static WindowContext getContext(long hwnd) {
        return contexts.get(hwnd);
    }
}
